<template>
  <div class="base-info pl20">
    <el-form :model="form" ref="formRef" label-width="98" :rules="rules" style="width: 100%">
      <el-form-item label="商品型号" prop="modeCode">
        <el-input
          v-model.trim="form.modeCode"
          placeholder="请输入商品型号“如7x1234或沙发长款xx345”"
          maxlength="20"
          show-word-limit
          style="width: 80%"
          oninput="value = value.replace(/[!|@|#|$|%|^|&|*|+|~|`|,|.|！|￥]/g, '')"
        ></el-input>
      </el-form-item>

      <el-form-item
        label="商品主图"
        prop="picIdLen"
        :rules="
          form.productType === '1' || form.productType === '3'
            ? [
                { required: true, message: '请上传商品图片', trigger: ['blur', 'change'] },
                { validator: picIdLenValidator, trigger: ['blur', 'change'] }
              ]
            : []
        "
      >
        <div>
          <!-- 商品主图解释说明 -->
          <div class="label-tips">
            <el-popover placement="bottom-start" :width="500" trigger="hover" popper-class="mainprod-tips">
              <template #reference>
                <el-icon style="color: #86909c"><QuestionFilled /></el-icon>
              </template>
              <template #default>
                <p class="f12">主材<span style="color: #6d6f74">“正常标准商品会需要上传完整的产品图素材展示”</span></p>
                <p class="f12">
                  辅材<span style="color: #6d6f74">“非标品可以不用上传产品图素材同时也不会被搜索到，但在合同中可以引用”</span>
                </p>
                <p class="f12">其他<span style="color: #6d6f74">“正常标准商品会需要上传完整的产品图素材展示”</span></p>
              </template>
            </el-popover>
          </div>

          <el-input v-model="form.picIdLen" v-show="false"></el-input>
          <!-- 上传图片 -->
          <el-upload
            drag
            :disabled="FileList.length >= 8"
            class="upload-demo upload-card"
            v-model:file-list="imgFileList"
            ref="uploadImg"
            :show-file-list="true"
            multiple
            :limit="8"
            list-type="picture-card"
            :auto-upload="false"
            :on-change="
              (file, fileList) => {
                handleAvatarChangeIcon(file, fileList);
              }
            "
          >
            <div
              :class="{ notuse: FileList.length >= 8 ? true : false }"
              style="display: flex; flex-direction: column; align-items: center; color: #86909c"
            >
              <el-icon class="f24"><Plus /></el-icon>
              <p class="f12" style="line-height: 22px; color: #86909c">点击上传</p>
            </div>

            <template #file="{ file }">
              <div>
                <template v-if="file.img">
                  <img class="el-upload-list__item-thumbnail" :src="file.img" alt="" />
                </template>

                <span v-show="!file.img" class="f30">
                  <el-icon><Loading /></el-icon>
                </span>
                <span class="jzt-el-upload-list__item-actions">
                  <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                    <el-icon><Delete /></el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
          <p class="f12 mt10" style="color: #86909c">
            建议图片大于：800*800像素，首图为纯白底,数量8张，单张不超过5M,支持jpeg，jpg，png格式;主题鲜明、图片清晰、提升买家满意度
          </p>
        </div>
      </el-form-item>
    </el-form>
    <!-- <el-button type="primary" @click="getBaseInfo">获取基础数据</el-button> -->
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from "vue";
import { ElMessage } from "element-plus";
import useMultipartOssStore from "@/store/modules/multipartOssStore.js";
const ossStore = useMultipartOssStore();
import {
  getFolder,
  _debounce //防抖，多次频繁触发时，只执行最后一次
} from "@/utils/index";
import { Delete, View, Plus, Loading, CirclePlusFilled, QuestionFilled } from "@element-plus/icons-vue";
import Sortable from "sortablejs";
import { getcategoryList2, imgsUpload } from "@/apis/products/specifications";

const props = defineProps({
  categoryId: {
    type: String,
    default: ""
  },
  Enums: {
    type: Array,
    default: () => []
  },
  optionInfo: {
    type: Object,
    default: () => {}
  }
});
const _optionInfo = ref({});
const sellPointList = ref([]); //卖点列表
const productCompareList = ref([]); //线上同款
const coverList = ref([]); //封面产品
const recommendList = ref([]); //设计推荐
const vrRef = ref();

watch(
  () => props.categoryId,
  val => {
    if (val) {
      form.value.categoryId = val;
    }
  }
);
watch(
  () => props.optionInfo,
  val => {
    if (val) {
      _optionInfo.value = JSON.parse(JSON.stringify(val));
      console.log("baseinfo的详情数据====", _optionInfo.value);
      dateReview(); //数据回显
    }
  },
  { deep: true }
);
watch(
  () => props.Enums,
  val => {
    if (val) {
      // console.log("数据字典====", val);
      //商品类型-shop_product_type
      shopProductTypes.value = val.filter(item => {
        if (item.dictType === "shop_product_type") {
          return item;
        }
      })[0].dictDataList;
      form.value.productType = shopProductTypes.value[0].dictValue;
    }
  }
);

//封面产品-选择商品之后的submit回调
const selectCoverProdSubmit = prods => {
  coverList.value = prods;
  console.log("这里是选中的封面产品", prods);
};

//设计推荐-选择商品之后的submit回调
const selectRecommendProdSubmit = prods => {
  recommendList.value = prods;
  console.log("这里是设计推荐产品", prods);
};

const toPath = (item, index) => {
  // https://detail.tmall.com/item.htm?spm=a21n57.sem.p4pright.4.10d03903FssYt6&priceTId=2150445117321707643801586e4d9b&utparam=%7B%22aplus_abtest%22%3A%22efd02d32db1e2275b6e6c29b4f381c3f%22%7D&id=822719475216&ns=1&xxc=ad_ztc
  const url = item.url;
  if (!url) return;
  window.open(url, "_");
  console.log("页面跳转", item);
};

//新增一个线上同款
const addOnlineSame = () => {
  productCompareList.value.push({});
};
//删除一个线上同款
const delOnlineSame = (item, index) => {
  productCompareList.value.splice(index, 1);
  console.log("线上同款===", productCompareList.value);
};

const picIdLenValidator = (rule, value, callback) => {
  if (value > 0) {
    callback();
  } else {
    callback("请上传商品图片");
  }
};
const form = ref({ categoryId: "", picIdLen: 0, isShow: 1 });
const formRef = ref();
const products = ref([]);
const treeSelectRef = ref();
const defaultNode = ref({});
const rules = ref({
  categoryId: [{ required: true, message: "请选择商品分类", trigger: "blur" }],
  productName: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  modeCode: [{ required: true, message: "请输入商品型号", trigger: "blur" }]
  // picIdLen: [
  //   { required: true, message: "请上传商品图片", trigger: ["blur", "change"] },
  //   { validator: picIdLenValidator, trigger: ["blur", "change"] }
  // ],
  // sliderVedioId: [{ required: true, message: "请上传商品视频", trigger: ["blur", "change"] }]
});
const FileList = ref([]); //商品图片list
const imgFileList = ref([]); //编辑时商品图片list
const videoList = ref([]); //商品视频list
const shopProductTypes = ref([]); //商品类型（数据字典） 1-主材；2-辅材；3-其他；

onMounted(() => {
  getProducts();

  initDragSort();
});

watch(
  () => FileList.value,
  val => {
    console.log("文件长度变化了===", val);
    form.value.picIdLen = val.length;
  },
  { deep: true }
);
watch(
  () => videoList.value,
  val => {
    console.log("视频变化了===", val);
    form.value.sliderVedioId = val[0].uid;
  },
  { deep: true }
);

//更换商品类型 （数据字典） 1-主材；2-辅材；3-其他；
const changeProType = val => {
  // console.log("商品类型改变了===", val);
  if (val === "2") {
    nextTick(() => {
      formRef.value.clearValidate(["picIdLen"]);
    });
  }
};

// 编辑时的数据回显
const dateReview = () => {
  const { editDetailInfo } = _optionInfo.value;
  form.value.categoryId = editDetailInfo.categoryId;
  form.value.productName = editDetailInfo.productName; //商品名称
  form.value.modeCode = editDetailInfo.modeCode; //商品型号
  // form.value.isShow = editDetailInfo.isShow; //商品显示销量
  form.value.productType = String(editDetailInfo.productType); //商品类型

  coverList.value = editDetailInfo.productCoverList; //编辑的时候，封面产品数据设置默认值
  recommendList.value = editDetailInfo.productRecommendList; //编辑的时候，设计推荐数据设置默认值

  /**图片回显 */
  const imgList = [];
  for (let index in editDetailInfo.sliderPicUrlList) {
    imgList.push({
      url: editDetailInfo.sliderPicUrlList[index],
      img: editDetailInfo.sliderPicUrlList[index],
      uid: editDetailInfo.sliderPicIdList[index]
    });
  }
  imgFileList.value = imgList;
  FileList.value = imgList;
  form.value.picIdLen = imgFileList.value.length;

  /**视频回显 */
  videoList.value = [
    { url: editDetailInfo.sliderVedioUrl, video: editDetailInfo.sliderVedioUrl, uid: editDetailInfo.sliderVedioId }
  ];
  form.value.sliderVedioId = editDetailInfo.sliderVedioId;

  //卖点回显 shopProductSeIIingPointDTOS
  sellPointList.value = editDetailInfo.shopProductSellingPointDTOS || [];
  // console.log("卖点回显", editDetailInfo.shopProductSellingPointDTOS);

  //线上同款回显，productCompareList
  productCompareList.value = editDetailInfo.productCompareList || [];
};

const getProducts = () => {
  getcategoryList2({ searchkey: "" }).then(res => {
    if (res.code === 200) {
      // console.log("这是商品分类====", res.data);
      products.value = res.data;
    }
  });
};
const breadList = ref([]);
const handleNodeClick = node => {
  // 最终的数据
  breadList.value = [];
  //  获取点击当节点的dom的信息
  let selectNode = treeSelectRef.value.getNode(node);
  // 调用递归函数
  platform(selectNode);
  console.log("选中的节点===", breadList.value);
};
// 递归函数
const platform = node => {
  if (!node?.parent) {
    return;
  }
  breadList.value.unshift(node.data);
  //调用递归
  platform(node?.parent);
};

const handleRemove = file => {
  console.log("移除===", file);
  uploadImg.value.handleRemove(file);
};

// 支持拖拽排序
const initDragSort = () => {
  const el = uploadImg.value.$el.querySelectorAll(".el-upload-list")[0];
  Sortable.create(el, {
    onEnd: ({ oldIndex, newIndex }) => {
      // 交换位置
      const arr = FileList.value;
      const page = arr[oldIndex];
      arr.splice(oldIndex, 1);
      arr.splice(newIndex, 0, page);
      console.log("拖拽后的文件list===", FileList.value);
    }
  });
};

//添加一个卖点项
const addPoint = () => {
  if (sellPointList.value.length < 3) {
    // sellPointList.value.push({ delTag: 0 });
    sellPointList.value.push({});
  } else {
    ElMessage({
      message: "最多允许添加3个卖点",
      type: "error",
      offset: 60
    });
  }
};

//删除一个卖点项
const delPoint = (item, index) => {
  // if (sellPointList.value.length <= 1) return;
  sellPointList.value.splice(index, 1);

  // if (props.optionInfo.actionType === "add") {
  //   // form.value.buinessMerchantAddress.splice(index, 1);
  //   // form.value._buinessAddress.splice(index, 1);
  //   sellPointList.value.splice(index, 1);
  //   // producerList.value = _producerList;
  // } else {
  //   item.delTag = 1;
  // }

  console.log("卖点===", sellPointList.value);
};

//====================================图片上传========================================================================================

const uploadImg = ref();
const uploadVideo = ref();
// const imgIsReady = ref(false);
const handleAvatarChangeIcon = _debounce(async (file, fileList, type = "img") => {
  //选中文件触发的change事件
  console.log("触发文件上传==", fileList);
  let _fileList = fileList.filter(item => item.status === "ready"); //未上传成功的图片
  const flag = await fileType(type, type === "img" ? _fileList : [file]);
  if (!flag) {
    const errorFile = [];
    const successFile = [];
    if (type === "img") {
      ElMessage({
        message: "只能上传jpeg，jpg，png图片文件，大小不超过5M",
        type: "error",
        offset: 60
      });
      for (let item of _fileList) {
        if (!(item.raw.type === "image/jpeg" || item.raw.type === "image/png") || item.raw.size > 1024 * 1024 * 5) {
          errorFile.push(item);
        } else {
          successFile.push(item);
        }
      }
      // const errorFile = _fileList.filter(item => !(item.raw.type === "image/jpeg" || item.raw.type === "image/png"));
      for (let item of errorFile) {
        uploadImg.value.handleRemove(item);
      }
    } else if (type === "video") {
      ElMessage({
        message: "只能上传视频文件，并且视频时长不超过45秒，大小不超过100M",
        type: "error",
        offset: 60
      });
      for (let item of _fileList) {
        if (!(item.raw.type === "video/mp4") || item.raw.size > 1024 * 1024 * 100) {
          errorFile.push(item);
        } else {
          successFile.push(item);
        }
      }
      // const errorFile = _fileList.filter(item => !(item.raw.type === "video/mp4"));
      for (let item of errorFile) {
        uploadVideo.value.handleRemove(item);
      }
      return;
    }
    if (successFile.length <= 0) return;
  }
  //   imgIsReady.value = false;
  if (type === "img") {
    FileList.value = fileList;

    for (let item of _fileList) {
      await customUpload(item, { file: item }, type);
    }
  } else {
    // videoList.value = fileList;
    videoList.value = [file];

    for (let item of videoList.value) {
      await customUpload(item, { file: item }, type);
    }
  }
}, 100);
/**
 * 校验文件类型
 */
const fileType = async (type, fileList) => {
  let flag = true;
  if (type === "img") {
    for (let item of fileList) {
      if (!((item.raw.type === "image/jpeg" || item.raw.type === "image/png") && item.raw.size <= 1024 * 1024 * 5)) {
        flag = false;
      }
      if (!(item.raw.type === "image/jpeg" || item.raw.type === "image/png")) {
        flag = false;
      }
    }
  } else if (type === "video") {
    for (let item of fileList) {
      if (!(item.raw.type === "video/mp4" && item.raw.size <= 1024 * 1024 * 100)) {
        flag = false;
      }
      if (item.raw.type === "video/mp4") {
        await getTimes(item.raw);
        // console.log("视频的时长===", item.raw.size <= 1024 * 1024 * 100, videoTime.value);
        if (!(videoTime.value <= 45)) {
          flag = false;
        }
      }
    }
  }
  return flag;
};
/**
 * 获取视频时间长度
 */
const videoTime = ref(0);
const getTimes = async file => {
  let content = file;
  //获取录音时长
  let url = URL.createObjectURL(content);
  //经测试，发现audio也可获取视频的时长
  let audioElement = new Audio(url);
  console.log(2222);
  await new Promise((resolve, reject) => {
    audioElement.addEventListener("loadedmetadata", _event => {
      //保存获取时间长度
      videoTime.value = parseInt(audioElement.duration);
      resolve("时长获取成功");
    });
  });
};
/**
 * 上传
 */
const getFileName = name => {
  const arr = name.split(".");
  const _arr = JSON.parse(JSON.stringify(arr));
  let _name = "";
  let _suffix = "";
  if (arr.length > 2) {
    _arr.splice(_arr.length - 1, 1);
    _name = _arr.join(".");
    _suffix = arr[arr.length - 1];
  } else {
    _name = arr[0];
    _suffix = arr[1];
  }
  const folder = getFolder();
  return folder + _name + new Date().getTime() + "." + _suffix;
};
const customUpload = async (item, option, type) => {
  // 合并已上传和当前上传文件

  const objName = getFileName(option.file.name);
  await ossStore
    .submit(objName, option.file.raw)
    .then(async res => {
      await ossStore.setACL(objName, fileReadRole.publicRead);
      res.fileUrl = await ossStore.signatureUrl(objName);
      console.log("文件上传成功，地址为===", res.fileUrl.split("?")[0]);
      if (type === "img") {
        item["img"] = res.fileUrl.split("?")[0];
      } else {
        item["video"] = res.fileUrl.split("?")[0];
        console.log("视频===", videoList.value);
      }
      item["folder"] = objName;

      const Option = JSON.parse(JSON.stringify(option));
      uploadIMG(Option); //图片上传到业务端
    })
    .catch(err => {
      alert(JSON.stringify(err));
    });
};

//将图片上传到业务端服务
const uploadIMG = option => {
  const nameArr = option.file.name.split(".");
  const uploadArr = [
    {
      fileId: option.file.uid,
      objectName: option.file.folder, //目录＋文件名称
      url: option.file.img || option.file.video,
      access: "public-read",
      fileName: option.file.name, //文件名称
      bucketName: "51-jzt-dev",
      size: option.file.size,
      type: true,
      suffix: nameArr[nameArr.length - 1]
    }
  ];
  imgsUpload(uploadArr).then(res => {
    console.log(909090, res);
  });
};
const fileReadRole = {
  defaultRole: "",
  privateRole: "private",
  publicRead: "public-read",
  publicReadWrite: "public-read-write"
};

const getBaseInfo = () => {
  // const { imgOrVideoArr, vrArr } = vrRef.value.getFileData();

  return new Promise((resolve, reject) => {
    formRef.value.validate((valid, fields) => {
      if (valid) {
        const baseInfo = {
          categoryId: form.value.categoryId, //商品分类
          productName: form.value.productName, //商品名
          modeCode: form.value.modeCode, //商品型号
          sliderPicIdList: FileList.value.map(item => String(item.uid)), //商品图片id集合
          sliderVedioId: videoList.value.length > 0 ? String(videoList.value[0].uid) : "", //商品视频id集合
          // isShow: form.value.isShow
          productType: String(form.value.productType),
          shopProductSellingPointDTOS: sellPointList.value, //卖点list
          productCompareList: productCompareList.value, //线上同款,
          productCoverList: coverList.value, //封面产品
          productRecommendList: recommendList.value //设计推荐
          // productLiveList: imgOrVideoArr, //实拍图
          // productVrList: vrArr //vr
        };
        console.log("基础数据baseInfo===", baseInfo);
        resolve(baseInfo);
      } else {
        console.log("error submit!", fields);
        Object.keys(fields).forEach((key, i) => {
          if (i == 0) {
            const firstFiled = fields[key][0].field;
            formRef.value.scrollToField(firstFiled);
          }
        });
      }
    });
  });
};
defineExpose({
  getBaseInfo
});
</script>

<style lang="scss">
.mainprod-tips {
  position: fixed !important;
}
</style>
<style lang="scss" scoped>
:deep(.el-upload-dragger) {
  padding: 0;
  height: 80px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-color: #dcdfe6 !important;
}
.label-tips {
  position: absolute;
  left: -98px;
  top: 1px;
}
p {
  color: #131414;
  line-height: 22px;
}
.notuse {
  cursor: not-allowed;
}
:deep(.online-wrap) {
  .el-form-item__content {
    .el-icon.del-icon {
      vertical-align: middle;
    }
    .add-btn {
      width: calc(60% - 48px);
      height: 32px;
      line-height: 32px;
      border: 1px solid #dcdfe6;
      display: flex;
      align-items: flex-end;
      .el-button {
        width: 100%;
        height: 30px;
        line-height: 30px;
        justify-content: flex-start;
      }
    }
  }
}
:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 80px;
  height: 80px;
}
.el-upload-list__item {
  & > div {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
:deep(.avatar-uploader) {
  .el-upload.el-upload--picture-card {
    width: 200px;
    height: 120px;
  }
}
.sell-wrap {
  width: 60%;
  :deep(.editor-com) {
    & > div {
      border: none !important;
      & > div {
        border-bottom: 1px solid #e1e6ed !important;
      }
      .w-e-text-container,
      .w-e-bar.w-e-bar-show.w-e-toolbar {
        background-color: #f2f3f5;
      }
    }
  }
  .sell-item {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    & > div {
      flex: 1;
      border: 1px solid #e1e6ed;
      border-radius: 4px;
      padding: 10px 20px;
      width: calc(100% - 76px);
    }
    & > span {
      width: 14px;
    }
  }
}
</style>
